package org.xxforest.game.core.scenes.scene2d.graphics;

import org.xxforest.game.core.XX;
import org.xxforest.game.core.scenes.scene2d.XXNode;
import org.xxforest.game.core.scenes.scene2d.graphics.tiled.XXTileAtlas;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.tiled.TiledLayer;
import com.badlogic.gdx.graphics.g2d.tiled.TiledLoader;
import com.badlogic.gdx.graphics.g2d.tiled.TiledMap;

public class XXTiledMap extends XXNode{
	
	private Camera camera ;
    private TiledMap map;
    private XXTileAtlas atlas;

	public XXTiledMap(TiledMap tiledMap, XXTileAtlas xxTileAtlas) {
		map = tiledMap;;
		atlas = xxTileAtlas ;
	}

	@Override
	public void draw(SpriteBatch batch, float delta) {
		int tileHeight = map.tileHeight;
		int tileWidth = map.tileWidth;
		
		int appearHeightGird = (int)(camera.viewportHeight * 1.5f) / tileHeight + 3;
		int appearWidthGird = (int)(camera.viewportWidth * 1.5f) / tileWidth + 3;
		
		int fromHeightGird = (int) (camera.position.y - camera.viewportHeight ) / tileHeight  ;
		int fromWidthGird = (int) (camera.position.x - camera.viewportWidth) / tileWidth ;
		
		int toHeightGird = fromHeightGird + appearHeightGird ;
		int toWidthGird = fromWidthGird + appearWidthGird;
		
		toHeightGird = Math.max(0, toHeightGird);
		toWidthGird = Math.max(0, toWidthGird);
		
		fromWidthGird = Math.max(0, fromWidthGird);
		fromHeightGird = Math.max(0, fromHeightGird);
		
		toHeightGird = Math.min(map.height, toHeightGird);
		toWidthGird = Math.min(map.width, toWidthGird);
		
		fromHeightGird = Math.min(map.height, fromHeightGird);
		fromWidthGird = Math.min(map.width, fromWidthGird);
		
		for(TiledLayer tiledLayer : map.layers){
			int dry = toHeightGird ;
			int fhg = map.height - toHeightGird ;
			int thg = map.height - fromHeightGird ;
			for(int y = fhg  ; y < thg  ; y ++ ){
				dry --;
				int [] tiles = tiledLayer.tiles[y] ;
				for(int x = fromWidthGird ; x < toWidthGird ; x ++ ){
					if(tiles[x] == 0){
						continue ;
					}
					batch.draw(atlas.getRegion(tiles[x]), x * tileWidth  , dry * tileHeight , tileWidth, tileHeight);
				}
			}
		}
	}
	
	public String getTileProperty(int layerIndex , float x , float y , String name){
		TiledLayer tiledLayer = map.layers.get(layerIndex);
		int ty = map.height - (int)y/map.tileHeight;
		return map.getTileProperty(tiledLayer.tiles[ty][(int)x/map.tileWidth], "aa") ;
	}

	@Override
	public void onCreate() {
		this.camera = XX.director.getCamera() ;
	}
	
	public static XXTiledMap create(String tmxFile , String atlasPath) {
		TiledMap tiledMap = TiledLoader.createMap(Gdx.files.internal("map/m.tmx"));
		return new XXTiledMap(tiledMap ,new XXTileAtlas(tiledMap, Gdx.files.internal("map/")));
	}
}
